import { defineStore } from 'pinia'
import { requestLogin, requestUserInfo, requestLogout } from '@/service/api/user'
import { useStorage, useStorageType, useCrypto } from '@/utils'
import { LOGIN_PATH, TOKEN } from '@/constants'
import router from '@/router'
import { ElMessage } from 'element-plus/es'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null // 用户信息
  }),
  actions: {
    /**
     * 用户登录操作
     * @param loginForm
     */
    async loginAction(loginForm: any) {
      /** *********** 临时代码 ********** **/
      useStorage.setItem(TOKEN, 'Test Token', useStorageType.Cookies)
      await router.replace('/')
      return
      /** *********** 临时代码 ********** **/
      // 登录前密码加密
      // eslint-disable-next-line no-unreachable
      loginForm.password = useCrypto.encrypt(loginForm.password, 'user')
      const { msg: token } = await requestLogin(loginForm)
      // 记住我 保存 token 免登录
      useStorage.setItem(TOKEN, token, useStorageType.Cookies)
      // 获取用户信息
      await this.getUserInfoAction()
      await router.replace('/')
    },
    /**
     * 获取用户信息
     */
    async getUserInfoAction() {
      const { data: userInfo } = await requestUserInfo()
      this.userInfo = userInfo
    },
    /**
     * 退出登录操作
     */
    async logoutAction() {
      const { msg } = await requestLogout()
      if (!msg) ElMessage.success('退出成功')
      /* 清空缓存 */
      // useUserStore().$reset()
      useStorage.removeItem(TOKEN, useStorageType.Cookies)
      this.userInfo = null
      await router.replace(LOGIN_PATH)
    }
  },
  persist: {
    key: 'user',
    storage: window.localStorage,
    paths: ['userInfo']
  }
})
